{% extends "sitebase.html" %}
{% block title %}Whole Campus{% endblock %}
{% block menu_5 %}
class="active"
{% endblock %}
{% block extra_scriptsCSS_imports %}
<link href="/site-media/anytime/anytimec.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="/site-media/flot/jquery.flot.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.stack.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.navigate.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.selection.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" src="/site-media/anytime/anytimec.js"></script>
<script type="text/javascript" src="/site-media/bootstrap/bootstrap-modal.js"></script>
<link rel="stylesheet" href="/site-media/jgauge/css/jgauge.css" type="text/css" /> <!-- CSS for jGauge styling. -->
<!--[if IE]><script type="text/javascript" language="javascript" src="js/excanvas.min.js"></script><![endif]--> <!-- Extends canvas support to IE. (Possibly buggy, need to look into this.) -->
<script type="text/javascript" src="/site-media/jgauge/js/jQueryRotate.min.js"></script> <!-- jQueryRotate plugin used for needle movement. -->
<script type="text/javascript" src="/site-media/jgauge/js/jgauge-0.3.0.a3.js"></script> <!-- jGauge JavaScript. -->
<script type="text/javascript" src="/site-media/psMathStats/psMathStats.min.js"></script>
<script type="text/javascript" src="/site-media/jquery-sparkline/jquery.sparkline.js"></script>


<!-- customs -->
<script type="text/javascript" src="/site-media/campenportJS/buildingpage/gaugeSetup.js"></script>
<script type="text/javascript" src="/site-media/campenportJS/smap/query.js"></script>
<script type="text/javascript" src="/site-media/campenportJS/buildingpage/statsCalc.js"></script>
{% endblock %}

{% block extra_css_inline %}
	.hero-unit {
		padding-top: 20px;
		padding-bottom: 20px;
		padding-right: 20px;
		padding-left: 20px;


	}

	footer {
		 margin-top: 0px; 
	}
{% endblock %}

{% block header_title %}
Whole Campus
{% endblock %}
{% block header_subtitle %}
Drag on the graph to zoom in.
{% endblock %}

{% block content_inside %}
<div class="hero-unit" style="min-height:610px;margin-top:0px;" id="graphMain">
<h2>Live Power Consumption Graph (Default 1 Day): </h2> Start Time: <input class="span4" type = "text" id="date2" size=36>&nbsp; &nbsp;  End Time: <input class="span4" type="text" id="date" size=36> &nbsp; &nbsp; <input type = "button" class="btn primary" value = "Load/Refresh Data" id="refresh"> &nbsp; &nbsp;<input type="checkbox" id="autoup" name="autoup" value="10" checked /> Autoupdate (15 min)
<br><br>
<div id="graph" >
<!-- contains graph generated by flot -->
<div id="placeholder" style = "position:absolute;width:900px;height:520px;">
    
</div><div id="loading" style="position:absolute;width:300px;top:450px;left:50%;margin-left:-150px;text-align:center;padding:7px 0 0 0;font:bold 11px Arial, Helvetica, sans-serif;">  
    Loading data, please wait..  
    <img src="/site-media/images/ajax-loader.gif" alt="loading.." />  
    </div> 
</div>
</div>
<div id="row"><h3>About our Data:</h3><div class="hero-unit"><p>We provide data for <b>{{ BUILDING_COUNT }} out of {{ ACTUAL_BUILDING_COUNT }}</b> buildings on the Berkeley campus or <b>{{ BUILD_PERCENT}}%</b> of buildings.</p></div><br><h3>Want More Data?</h3><div class="hero-unit"><p>You can find a much larger quantity of data at <a href="http://new.openbms.org">new.openbms.org</a></p></div><br><h3>Found a problem with the site?</h3><div class="hero-unit"><p>Let us know by clicking the green icon at the lower right. If you have a specific bug report, post an issue on the project's repository at <a href="http://code.google.com/p/campenport">code.google.com</a></p></div></div>
{% endblock %}
{% block extend_contact_url %}{{ A_SHORT_NAME }}{% endblock %}
{% block random_extras %}
<script type="text/javascript">
//time setup
var datefmt = "%W %M %e, %Y %H:%i";
var converter = new AnyTime.Converter( { format: datefmt });
var nowDate = new Date();
$("#date").val(converter.format(nowDate));
var startDate = new Date();
startDate.setTime(nowDate - 86400000);
$("#date2").val(converter.format(startDate));
AnyTime.picker( "date", { format: datefmt, firstDOW: 0 } );
AnyTime.picker( "date2", { format: datefmt, firstDOW: 0 } );
//end time setup

function scrollDownTo(itemID){
     	$('html,body').animate({scrollTop: $("#"+itemID).offset().top-40},'slow');
}
function scrollToTop(){
     	$('html,body').animate({scrollTop: 0},'slow');
}


$(function () {
              $("a[rel=popover]")
                .popover({
                  offset: 10
                })
                .click(function(e) {
                  e.preventDefault()
                })
            })

$(document).ready(function() {
	callgetLatestWholeCampus(1);
});

$("#refresh").click(function() {
	$("#placeholder").empty();
	$("#loading").show();
	callgetLatestWholeCampus(1);
});


function sendTodrawGraph(response){
	console.log(response);
	drawGraph(response);
}


function callgetLatestWholeCampus(lastActualkW){
	getLatestWholeCampus(sendTodrawGraph);
}

function getLatestWholeCampus(callback) {
	var converter = new AnyTime.Converter( { format: datefmt });
	var endtime = converter.parse($("#date").val()).getTime();
	var starttime = converter.parse($("#date2").val()).getTime();
	$.ajax({
		async: true,
		type: 'POST',
		url: '/ARDgetData/api/query?',
		error: function(response) {
			//start hacky fix for streaming
			a = response.responseText.split("}}}]");
			//console.log(a);
			for(x = 0; x<a.length; x++){
				a[x] += "}}}]";
			}
			a.pop();
			for(x = 0; x<a.length; x++){
				a[x] = $.parseJSON(a[x]);
			}
			for(x = 1; x<a.length; x++){
				a[0][0]['Readings'] = a[0][0]['Readings'].concat(a[x][0]['Readings']);
			}
			//end hacky fix for streaming
			drawGraph(a[0]);
				},
		data: "apply nansum(axis=1) < paste < window(first, field='minute', width=15) < units to data in (" + (starttime) + " ," + endtime + ") streamlimit 10000 where Metadata/Extra/System = 'electric'  and Metadata/Location/Building like '%' and ((Properties/UnitofMeasure = 'kW' or Properties/UnitofMeasure = 'Watts') or Properties/UnitofMeasure = 'W') and not Metadata/Extra/Operator like 'sum%' and not Path like '%demand'",
		success: function(response) {
			callback(response);
		}
	});
}

function drawGraph(inputData, typeData, flatlineAvg){

	needTzOffset = new Date();
	tzOffset = needTzOffset.getTimezoneOffset()*60000
	
		for (y=0; y<inputData[0]['Readings'].length; y++){
			inputData[0]['Readings'][y][0] = inputData[0]['Readings'][y][0]-tzOffset;
			inputData[0]['Readings'][y][1] = inputData[0]['Readings'][y][1]/1000;
		}
	/*
	if (flatlineAvg != 0){
	flatlineAvg[0][0] -= tzOffset;
	flatlineAvg[1][0] -= tzOffset;
	}
	//end fix timezone offset for flot*/
	var data = [{label: "Whole Campus", "data": inputData[0]['Readings']}];
	//console.log(data);
/*	for (ind3 = 0; ind3 < inputData.length; ind3++) {
		data.push({label:typeData[ind3], "data":inputData[ind3]['Readings']});
	}
	if (flatlineAvg != 0 && flatlineAvg[0][1]!=0){
	data.push({label:"Constant Average", "data":flatlineAvg});
	} */
	var options = {
			colors: ["blue", "black"],
        	legend: { noColumns: 2 },
        	xaxis: { tickDecimals: 0, mode:"time" },
        	selection: { mode: "x" },
			grid: {hoverable: true, clickable: true},
			xaxes: [{
				axisLabel: 'Time',
			}],
			yaxes: [{
				position: 'left',
				axisLabel: 'Power Consumption (MW)',
			}],
			series: {shadowSize: 0},
    	};

	var placeholder = $("#placeholder");

	placeholder.bind("plotselected", function (event, ranges) {
		$("#selection").text(ranges.xaxis.from.toFixed(1) + " to " + ranges.xaxis.to.toFixed(1));
		plot = $.plot(placeholder, data, $.extend(true, {}, options, { xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to } }));
	});

	placeholder.bind("plotunselected", function (event) {
		$("#selection").text("");
	});


var previousPoint = null;
    $("#placeholder").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

        if (true) {
            if (item) {
                if (previousPoint != item.dataIndex) {
                    previousPoint = item.dataIndex;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(2),
                        y = item.datapoint[1].toFixed(2);
                    
					var tempdate = new Date(x/1+tzOffset);
                    showTooltip(item.pageX, item.pageY,
                                item.series.label + " on " + converter.format(tempdate)  + " was " + y + " MW");
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
        }
    });

    $("#placeholder").bind("plotclick", function (event, pos, item) {
        if (item) {
            $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
            plot.highlight(item.series, item.datapoint);
        }
    });

	$("#loading").hide()
	var plot = $.plot(placeholder, data, options);
	return inputData;
}

function showTooltip(x, y, contents) {
		if (x<800){
			x = x;
		}
		else if (x<1100){
			x = x-300;
		}
		else{
			x = x-560;
		}
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            border: '1px solid #fdd',
            padding: '5px',
            'background-color': '#000',
			'color': '#FFF',
            opacity: 0.70,
			'font-size': '140%',
        }).appendTo("body").fadeIn(200);
}




</script>
{% endblock %}
